package cn.gjxblog.security.browser;

import cn.gjxblog.core.properties.SecurityProperties;
import cn.gjxblog.security.browser.common.SimpleHttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/1/16 9:37
 */
@RestController
public class BrowserSecurityController {

    private Logger logger = LoggerFactory.getLogger(BrowserSecurityController.class);

    @Autowired
    private SecurityProperties securityProperties;

    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleHttpResult requireAuthentication(HttpServletRequest request, HttpServletResponse response, HttpSessionRequestCache requestCache, DefaultRedirectStrategy redirectStrategy) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        String requestURI = request.getRequestURI();
        System.out.println("请求的url的是："+requestURI);
        if(savedRequest!=null){
            String redirectUrl = savedRequest.getRedirectUrl();
            logger.info("引发跳转的请求是:"+redirectUrl);

            if(StringUtils.endsWithIgnoreCase(redirectUrl,".html")){
                redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getLoginPage());
            }
        }
        return new SimpleHttpResult("访问的资源需要认证，请引导用户到登录页面");
    }

}
